from http.client import HTTPException

from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_ningmengyun.service.product_service import ProductService
from module_sale.dao.packaging_dao import PackagingDao
from module_sale.entity.vo.packaging_vo import DeletePackagingModel, PackagingModel, PackagingPageQueryModel, \
    PackagingAddModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil
from fastapi import Request


class PackagingService:
    """
    包装费用管理模块服务层
    """

    @classmethod
    async def get_packaging_list_services(
        cls, query_db: AsyncSession, query_object: PackagingPageQueryModel, is_page: bool = False
    ):
        """
        获取包装费用管理列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 包装费用管理列表信息对象
        """
        packaging_list_result = await PackagingDao.get_packaging_list(query_db, query_object, is_page)

        return packaging_list_result

    @classmethod
    async def check_packaging_item_unique_services(cls, query_db: AsyncSession, page_object: PackagingModel):
        """
        检查包装方式记录id是否唯一service

        :param query_db: orm对象
        :param page_object: 包装费用管理对象
        :return: 校验结果
        """
        packaging_id = -1 if page_object.packaging_id is None else page_object.packaging_id
        packaging_list = await PackagingDao.get_packaging_list_by_info(
            query_db,
            PackagingModel(
                productId=page_object.product_id,
                year=page_object.year,
                asId=page_object.as_id
            ))

        if packaging_id == -1 and len(packaging_list) >= 1:
            return CommonConstant.NOT_UNIQUE
        elif packaging_id > 0 and len(packaging_list) >= 2:
            return CommonConstant.NOT_UNIQUE
        return CommonConstant.UNIQUE


    @classmethod
    async def add_packaging_services(cls, query_db: AsyncSession, page_object: PackagingAddModel, req:Request):
        """
        新增包装费用管理信息service

        :param query_db: orm对象
        :param page_object: 新增包装费用管理对象
        :param req:
        :return: 新增包装费用管理校验结果
        """
        try:
            as_id = str(page_object.as_id)
            for product_id in page_object.product_ids:
                product_item  = await  ProductService.product_detail_services(req, str(product_id), as_id )

                packaging_object = PackagingModel()
                packaging_object.product_id = product_id
                packaging_object.product_name = product_item.prod.name
                packaging_object.product_weight = product_item.unit.rate
                packaging_object.as_id = page_object.as_id
                packaging_object.create_by = page_object.create_by
                packaging_object.update_by = page_object.update_by
                packaging_object.create_time = page_object.create_time
                packaging_object.update_time = page_object.update_time
                packaging_object.materials_cost=page_object.materials_cost
                packaging_object.chilling_fee=page_object.chilling_fee
                packaging_object.year = page_object.year
                packaging_object.del_status = 0
                if_unique = await cls.check_packaging_item_unique_services(query_db, packaging_object)
                if if_unique == CommonConstant.NOT_UNIQUE:
                    raise HTTPException("选中的商品："+ packaging_object.product_name + "已经设置过在当前账套今年的包材明细费，请编辑记录进行价格修改。")
                await PackagingDao.add_packaging_dao(query_db, packaging_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_packaging_services(cls, query_db: AsyncSession, page_object: PackagingModel):
        """
        编辑包装费用管理信息service

        :param query_db: orm对象
        :param page_object: 编辑包装费用管理对象
        :return: 编辑包装费用管理校验结果
        """
        edit_packaging = page_object.model_dump(exclude_unset=True, exclude={'create_by', 'create_time', 'del_status'})
        packaging_info = await cls.packaging_detail_services(query_db, page_object.packaging_id)
        if packaging_info.packaging_id:
            if not await cls.check_packaging_item_unique_services(query_db, page_object):
                raise HTTPException("选中的商品："+ packaging_info.product_name + "已经设置过在当前账套今年的包材明细费，请编辑记录进行价格修改。")
            try:
                await PackagingDao.edit_packaging_dao(query_db, edit_packaging)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='包装费用管理记录不存在')

    @classmethod
    async def delete_packaging_services(cls, query_db: AsyncSession, page_object: DeletePackagingModel):
        """
        删除包装费用管理信息service

        :param query_db: orm对象
        :param page_object: 删除包装费用管理对象
        :return: 删除包装费用管理校验结果
        """
        if page_object.packaging_ids:
            packaging_id_list = page_object.packaging_ids.split(',')
            try:
                for packaging_id in packaging_id_list:
                    await PackagingDao.delete_packaging_dao(query_db, PackagingModel(packagingId=packaging_id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入包装方式记录id为空')

    @classmethod
    async def packaging_detail_services(cls, query_db: AsyncSession, packaging_id: int):
        """
        获取包装费用管理详细信息service

        :param query_db: orm对象
        :param packaging_id: 包装方式记录id
        :return: 包装方式记录id对应的信息
        """
        packaging = await PackagingDao.get_packaging_detail_by_id(query_db, packaging_id=packaging_id)
        if packaging:
            result = PackagingModel(**CamelCaseUtil.transform_result(packaging))
        else:
            result = PackagingModel(**dict())

        return result

    @staticmethod
    async def export_packaging_list_services(packaging_list: List):
        """
        导出包装费用管理信息service

        :param packaging_list: 包装费用管理信息列表
        :return: 包装费用管理信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'packagingId': '包装方式记录id',
            'materialsCost': '包材费',
            'chillingFee': '人工及打冷费',
            'productId': '商品Ids',
            'year': '数据年份',
            'createBy': '创建人',
            'createTime': '创建时间',
            'updateBy': '更新人',
            'updateTime': '更新时间',
            'delStatus': '删除状态',
        }
        binary_data = ExcelUtil.export_list2excel(packaging_list, mapping_dict)

        return binary_data
